import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  InputNumber, 
  Select, 
  Button, 
  Space, 
  Card, 
  Row, 
  Col, 
  Switch, 
  message,
  Spin,
  Divider,
  Alert
} from 'antd';
import { 
  SaveOutlined, 
  PlusOutlined, 
  MinusCircleOutlined
} from '@ant-design/icons';
import type { FormInstance } from 'antd/es/form';

import type { 
  Product, 
  ProductFormData
} from '../../../types/product';
import {
  ProductCategory, 
  ProductCondition, 
  TransactionMethod
} from '../../../types/product';
import { 
  PRODUCT_CATEGORY_DISPLAY_NAMES, 
  PRODUCT_CONDITION_DISPLAY_NAMES,
  TRANSACTION_METHOD_DISPLAY_NAMES,
  validateProductData
} from '../../../types/product';

import ImageUploader from '../../common/ImageUploader';
import type { UploadFile } from 'antd/es/upload/interface';

const { TextArea } = Input;
const { Option } = Select;

interface ProductFormProps {
  /** 表单数据（编辑时传入） */
  initialData?: Product;
  /** 表单提交回调 */
  onSubmit?: (formData: ProductFormData) => Promise<void>;
  /** 表单取消回调 */
  onCancel?: () => void;
  /** 是否正在提交 */
  loading?: boolean;
  /** 表单标题 */
  title?: string;
  /** 是否禁用 */
  disabled?: boolean;
  /** 自定义学校列表 */
  schools?: string[];
  /** 自定义校区列表 */
  campuses?: string[];
}

/**
 * 商品表单组件
 * 支持发布和编辑商品，包含完整的表单验证和图片上传功能
 */
const ProductForm: React.FC<ProductFormProps> = ({
  initialData,
  onSubmit,
  onCancel,
  loading = false,
  title = '发布商品',
  disabled = false,
  schools = ['清华大学', '北京大学', '复旦大学', '上海交通大学', '浙江大学', '南京大学'],
  campuses = ['主校区', '东校区', '西校区', '南校区', '北校区']
}) => {
  const [form] = Form.useForm<ProductFormData>();
  const [submitting, setSubmitting] = useState(false);
  const [imageFiles, setImageFiles] = useState<UploadFile[]>([]);

  // 初始化表单数据
  useEffect(() => {
    if (initialData) {
      const formData: Partial<ProductFormData> = {
        title: initialData.title,
        description: initialData.description,
        price: initialData.price,
        originalPrice: initialData.originalPrice,
        category: initialData.category,
        condition: initialData.condition,
        transactionMethod: initialData.transactionMethod,
        tags: initialData.tags,
        isNegotiable: initialData.isNegotiable,
        isFreeShipping: initialData.isFreeShipping,
        shippingFee: initialData.shippingFee,
        stock: initialData.stock,
        isReturnable: initialData.isReturnable,
        returnPolicy: initialData.returnPolicy,
        school: initialData.location.school,
        campus: initialData.location.campus,
        address: initialData.location.address,
        longitude: initialData.location.longitude,
        latitude: initialData.location.latitude,
      };
      
      form.setFieldsValue(formData);
      
      // 转换图片数据
      if (initialData.images && initialData.images.length > 0) {
        const imageFiles: UploadFile[] = initialData.images.map((img, index) => ({
          uid: img.id || `img-${index}`,
          name: `image-${index}`,
          status: 'done' as const,
          url: img.url,
          thumbUrl: img.thumbnailUrl,
        }));
        setImageFiles(imageFiles);
      }
    }
  }, [initialData, form]);

  // 处理表单提交
  const handleSubmit = async (values: ProductFormData) => {
    if (submitting || disabled) return;

    try {
      setSubmitting(true);
      
      // 合并图片数据
      const imageUrls = imageFiles
        .filter(file => file.status === 'done' && file.response?.url)
        .map(file => ({
          id: file.uid,
          url: file.response?.url || file.url || '',
          thumbnailUrl: file.response?.thumbUrl || file.thumbUrl || '',
          uploadedAt: new Date(),
        }));

      const formData: ProductFormData = {
        ...values,
        images: imageUrls,
      };

      // 验证商品数据
      if (!validateProductData(formData)) {
        message.error('请检查表单数据是否完整');
        return;
      }

      await onSubmit?.(formData);
      message.success(initialData ? '商品更新成功' : '商品发布成功');
      
    } catch (error) {
      console.error('表单提交失败:', error);
      message.error(initialData ? '商品更新失败' : '商品发布失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 处理表单验证失败
  const handleFinishFailed = (errorInfo: any) => {
    console.log('表单验证失败:', errorInfo);
    message.error('请检查表单数据是否正确填写');
  };

  // 价格变化处理
  const handlePriceChange = (value: number | null) => {
    if (value && value > 0) {
      const currentPrice = form.getFieldValue('price');
      if (currentPrice && value < currentPrice) {
        form.setFieldValue('originalPrice', value);
      }
    }
  };

  // 包邮状态变化处理
  const handleFreeShippingChange = (checked: boolean) => {
    form.setFieldValue('isFreeShipping', checked);
    if (checked) {
      form.setFieldValue('shippingFee', undefined);
    }
  };

  // 标签管理
  const [tags, setTags] = useState<string[]>(initialData?.tags || []);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');

  const handleTagClose = (removedTag: string) => {
    const newTags = tags.filter(tag => tag !== removedTag);
    setTags(newTags);
    form.setFieldValue('tags', newTags);
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      const newTags = [...tags, inputValue];
      setTags(newTags);
      form.setFieldValue('tags', newTags);
    }
    setInputVisible(false);
    setInputValue('');
  };

  // 图片上传变化处理
  const handleImageChange = (files: UploadFile[]) => {
    setImageFiles(files);
    // 这里可以处理图片上传逻辑
  };

  return (
    <div className="product-form w-full flex justify-center">
      <Card 
        title={title} 
        className="w-full max-w-4xl mx-auto"
        extra={
          <Space wrap>
            <Button onClick={onCancel} disabled={submitting || disabled}>
              取消
            </Button>
            <Button 
              type="primary" 
              icon={<SaveOutlined />}
              loading={submitting || loading}
              onClick={() => form.submit()}
              disabled={disabled}
            >
              {initialData ? '更新商品' : '发布商品'}
            </Button>
          </Space>
        }
      >
        <Spin spinning={submitting || loading}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            onFinishFailed={handleFinishFailed}
            disabled={disabled}
            className="space-y-6 w-full"
          >
            {/* 基本信息区块 */}
            <Card title="基本信息" size="small" className="w-full">
              <Row gutter={16}>
                <Col xs={24}>
                  <Form.Item
                    name="title"
                    label="商品标题"
                    rules={[
                      { required: true, message: '请输入商品标题' },
                      { min: 2, max: 50, message: '标题长度应在2-50个字符之间' }
                    ]}
                  >
                    <Input 
                      placeholder="请输入商品标题，如：二手MacBook Pro 2020款" 
                      maxLength={50}
                      showCount
                    />
                  </Form.Item>
                </Col>

                <Col xs={24}>
                  <Form.Item
                    name="description"
                    label="商品描述"
                    rules={[
                      { required: true, message: '请输入商品描述' },
                      { min: 10, max: 500, message: '描述长度应在10-500个字符之间' }
                    ]}
                  >
                    <TextArea
                      rows={4}
                      placeholder="详细描述商品状况、使用情况、配件等信息"
                      maxLength={500}
                      showCount
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            <Divider />

            {/* 价格与库存区块 */}
            <Card title="价格与库存" size="small" className="w-full">
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    name="price"
                    label="价格（元）"
                    rules={[
                      { required: true, message: '请输入价格' },
                      { type: 'number', min: 0.01, message: '价格必须大于0' }
                    ]}
                  >
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="0.00"
                      min={0.01}
                      precision={2}
                      step={0.01}
                    />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="originalPrice"
                    label="原价（元）"
                  >
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="可选"
                      min={0.01}
                      precision={2}
                      step={0.01}
                      onChange={handlePriceChange}
                    />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="stock"
                    label="库存数量"
                    rules={[
                      { required: true, message: '请输入库存数量' },
                      { type: 'number', min: 1, max: 999, message: '库存数量应在1-999之间' }
                    ]}
                  >
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="1"
                      min={1}
                      max={999}
                    />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="isNegotiable"
                    label="是否支持议价"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="支持" unCheckedChildren="不支持" />
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            <Divider />

            {/* 商品分类区块 */}
            <Card title="商品分类" size="small" className="w-full">
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    name="category"
                    label="商品类别"
                    rules={[{ required: true, message: '请选择商品类别' }]}
                  >
                    <Select placeholder="请选择商品类别">
                      {Object.values(ProductCategory).map(category => (
                        <Option key={category} value={category}>
                          {PRODUCT_CATEGORY_DISPLAY_NAMES[category]}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="condition"
                    label="新旧程度"
                    rules={[{ required: true, message: '请选择新旧程度' }]}
                  >
                    <Select placeholder="请选择新旧程度">
                      {Object.values(ProductCondition).map(condition => (
                        <Option key={condition} value={condition}>
                          {PRODUCT_CONDITION_DISPLAY_NAMES[condition]}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="transactionMethod"
                    label="交易方式"
                    rules={[{ required: true, message: '请选择交易方式' }]}
                  >
                    <Select placeholder="请选择交易方式">
                      {Object.values(TransactionMethod).map(method => (
                        <Option key={method} value={method}>
                          {TRANSACTION_METHOD_DISPLAY_NAMES[method]}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="tags"
                    label="商品标签"
                  >
                    <div>
                      <div className="flex flex-wrap gap-2 mb-2">
                        {tags.map(tag => (
                          <span 
                            key={tag} 
                            className="inline-flex items-center px-2 py-1 bg-blue-100 text-blue-800 rounded text-sm"
                          >
                            {tag}
                            <MinusCircleOutlined 
                              className="ml-1 cursor-pointer" 
                              onClick={() => handleTagClose(tag)}
                            />
                          </span>
                        ))}
                      </div>
                      {inputVisible ? (
                        <Input
                          type="text"
                          size="small"
                          style={{ width: 100 }}
                          value={inputValue}
                          onChange={handleInputChange}
                          onBlur={handleInputConfirm}
                          onPressEnter={handleInputConfirm}
                        />
                      ) : (
                        <Button 
                          type="dashed" 
                          size="small" 
                          icon={<PlusOutlined />}
                          onClick={showInput}
                        >
                          添加标签
                        </Button>
                      )}
                    </div>
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            <Divider />

            {/* 图片上传区块 */}
            <Card title="商品图片" size="small" className="w-full">
              <div className="pt-4 pb-2">
                <div className="upload-section bg-gray-50 rounded-lg p-4 border border-gray-200">
                  <div className="mb-3">
                    <div className="text-sm text-gray-500">
                      点击或拖拽图片到此处上传， 支持最多上传 5 张图片，每张图片大小不超过 5MB
                    </div>
                  </div>
                  <Form.Item
                    name="images"
                    rules={[
                      { 
                        validator: () => {
                          if (imageFiles.length === 0) {
                            return Promise.reject(new Error('请至少上传一张商品图片'));
                          }
                          return Promise.resolve();
                        }
                      }
                    ]}
                  >
                    <ImageUploader
                      maxCount={5}
                      value={imageFiles}
                      onChange={handleImageChange}
                      placeholder="点击或拖拽上传"
                      disabled={disabled}
                    />
                  </Form.Item>
                </div>
                {imageFiles.length === 0 && (
                  <div className="text-red-500 text-sm mt-3 p-3 bg-red-50 rounded-lg border border-red-200">
                    <div className="flex items-center">
                      <span className="mr-2">⚠️</span>
                      请至少上传一张商品图片
                    </div>
                  </div>
                )}
              </div>
            </Card>

            <Divider />

            {/* 物流信息区块 */}
            <Card title="物流信息" size="small" className="w-full">
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    name="isFreeShipping"
                    label="是否包邮"
                    valuePropName="checked"
                  >
                    <Switch 
                      checkedChildren="包邮" 
                      unCheckedChildren="不包邮" 
                      onChange={handleFreeShippingChange}
                    />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="shippingFee"
                    label="邮费（元）"
                    dependencies={['isFreeShipping']}
                    rules={[
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!getFieldValue('isFreeShipping') && (!value || value <= 0)) {
                            return Promise.reject(new Error('请输入邮费'));
                          }
                          return Promise.resolve();
                        },
                      }),
                    ]}
                  >
                    <InputNumber
                      style={{ width: '100%' }}
                      placeholder="0.00"
                      min={0}
                      precision={2}
                      disabled={form.getFieldValue('isFreeShipping')}
                    />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="isReturnable"
                    label="是否支持退换货"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="支持" unCheckedChildren="不支持" />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="returnPolicy"
                    label="退换货政策"
                  >
                    <Input placeholder="如：7天无理由退换货" />
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            <Divider />

            {/* 位置信息区块 */}
            <Card title="位置信息" size="small" className="w-full">
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    name="school"
                    label="所在学校"
                    rules={[{ required: true, message: '请选择学校' }]}
                  >
                    <Select placeholder="请选择学校">
                      {schools.map(school => (
                        <Option key={school} value={school}>{school}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={12}>
                  <Form.Item
                    name="campus"
                    label="所在校区"
                  >
                    <Select placeholder="请选择校区">
                      {campuses.map(campus => (
                        <Option key={campus} value={campus}>{campus}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24}>
                  <Form.Item
                    name="address"
                    label="具体位置"
                  >
                    <Input placeholder="如：学生宿舍3号楼201室" />
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            {/* 提交按钮 */}
            <div className="flex flex-col sm:flex-row justify-center sm:justify-end gap-4 pt-6">
              <Button 
                onClick={onCancel} 
                disabled={submitting || disabled}
                className="w-full sm:w-auto"
              >
                取消
              </Button>
              <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={submitting || loading}
                  disabled={disabled}
                  icon={<SaveOutlined />}
                  size="large"
                  className="w-full sm:w-auto"
                >
                  {initialData ? '更新商品' : '发布商品'}
                </Button>
            </div>
          </Form>
        </Spin>
      </Card>
    </div>
  );
};

export default ProductForm;